<?php

class Admin_AuthController extends Zend_Controller_Action
{

    public function init()
    {
        if(Zend_Auth::getInstance( )->hasIdentity( )){
        	if('logout' != $this->_request->getActionName( )){
        		$this->_redirect('/admin/index/index');
        	}
        }
    }

    public function indexAction()
    {
        $this->_forward( 'login' );
    }

    public function loginAction()
    {
    	$this->view->pageTitle = 'כניסת מנהל מערכת';
    	$formParams = array(
    		'legendLabel' => $this->view->pageTitle 
    	);
        $this->view->form = new Admin_Form_Login($formParams );
        if($this->_request->isPost( )){
        	if($this->view->form->isValid( $this->_request->getPost( ))){
        		$_authAdapter = $this->_getAuthAdapter( $this->view->form->getValues());
        		$_auth = Zend_Auth::getInstance();
                $result = $_auth->authenticate( $_authAdapter );
            	if (false === $result->isValid()) {
                    $this->view->formError = 'שם משתמש או סיסמא שגויים';
                } else {
                    $data = $_authAdapter->getResultRowObject(null,'password');
                    $_auth->getStorage( )->write( $data );
                    $this->_redirect('/admin/index/index');
                }
        	}
        }
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity( );
        //$this->_forward( 'login' );
        $this->_redirect('/admin/index/index');
    }
    
    private function _getAuthAdapter( array $formData )
	{
		$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName( 'users' )
                    	->setIdentityColumn( 'username' )
                    	->setCredentialColumn( 'password' );
        
        $authAdapter->setIdentity($formData['username']);
        $authAdapter->setCredential(md5($formData['password']));

        return $authAdapter;
	}	


}





